<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
      </connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <el-tab-pane label="按日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计趋势"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按用户统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按用户统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="操作时间" show-overflow-tooltip prop="TransTime" width="160" ></el-table-column>
          <el-table-column label="用户名" show-overflow-tooltip prop="UserId" ></el-table-column>
          <el-table-column label="登录地址" show-overflow-tooltip prop="ClientIp" ></el-table-column>
          <el-table-column label="设备类型" show-overflow-tooltip prop="DeviceType" >
            <template slot-scope="{row}">
              <span v-show="row.DeviceType === '01'">PC客户端</span>
              <span v-show="row.DeviceType === '02'">WEB客户端</span>
              <span v-show="row.DeviceType === '03'">终端</span>
            </template>
          </el-table-column>
          <el-table-column label="认证类型" show-overflow-tooltip prop="LoginType" >
            <template slot-scope="{row}">
              <span v-show="row.LoginType === 'pwd'">密码</span>
              <span v-show="row.LoginType !== 'pwd'">{{ row.LoginType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="认证操作" show-overflow-tooltip prop="LoginOpt" >
            <template slot-scope="{row}">
              <span v-show="row.LoginOpt === 'login'">登录</span>
              <span v-show="row.LoginOpt === 'logout'">登出</span>
            </template>
          </el-table-column>
          <el-table-column label="认证结果" show-overflow-tooltip prop="LoginResult" >
            <template slot-scope="{row}">
              <span style="color:#67C23A" v-show="row.LoginResult === 0">成功</span>
              <span style="color:#F56C6C" v-show="row.LoginResult !== 0">失败</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="日志类型" show-overflow-tooltip prop="LogType" width="140"  ></el-table-column> -->
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="详情"
      :visible.sync="logDialog"
      v-el-drag-dialog
      width="1000px">
        <el-descriptions class="margin-top" :column="2"  border>
          <el-descriptions-item label="所在分区">{{ logList.PrimArea }}/{{ logList.SecondArea }}</el-descriptions-item>
          <el-descriptions-item label="从属部门">{{ logList.Department }}</el-descriptions-item>
          <el-descriptions-item label="校区名称">{{ logList.SchoolName }}</el-descriptions-item>
          <el-descriptions-item label="校区唯一编码">{{ logList.SchoolID }}</el-descriptions-item>
          <el-descriptions-item label="资产名称">{{ logList.DeviceName }}</el-descriptions-item>
          <el-descriptions-item label="资产唯一编码">{{ logList.DeviceID }}</el-descriptions-item>
          <el-descriptions-item label="检测时间">{{ logList.TransTime }}</el-descriptions-item>
          <el-descriptions-item label="核查项目"> 
                <span>{{ findBaselineLabel(logList.BlID) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="合规结论"> 
                <span :style="{color: logList.NeedFix === 0 ? '#67C23A' : '#F56C6C'}">{{logList.NeedFix === 0 ? '合规' : '不合规'}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="描述信息" :span="2">{{ logList.Descp }}</el-descriptions-item>
          <el-descriptions-item label="修复建议" :span="2">{{ findBaselineFixScheme(logList.BlID) }}</el-descriptions-item>
        </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="logDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart2.vue";
import piechart from "./components/piechart.vue";
import { parseTime, formatTime2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按日统计趋势',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      logDialog: false,
      logList: [],
      barchartData: [],
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      tableData:[],
      BaselineResultList: [],
      searchform:{},
      options:{},
      searchobj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 6,
          label: "操作用户",
          prop: "UserId",
          element: "el-input",
          placeholder: "请输入操作用户",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.UserId = val
            },
          },
        }
        // {
        //   col: 8,
        //   label: "资产选择",
        //   prop:"DeviceName",
        //   element: "el-cascader",
        //   initValue: "",
        //   placeholder: "请选择资产",
        //   options:[],
        //   props:{emitPath: true, checkStrictly: true, lazy: true, lazyLoad: that.lazyLoad},
        //   events: {
        //     input(val) {
        //       that.searchform.DeviceName = val
        //     },
        //   },
        // },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime() 
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // this.GetDeviceStatusSumTree()
  },
  methods: {
    // 获取子节点的资产
    async lazyLoad(node, resolve){
      if(node.level < 4){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SchoolName: node.label,
          }
        }
        const res = await connrequest('CenterGetDevice', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.DeviceName, value: item.DeviceID, level: 5, children: undefined} )
        })
        resolve(arr) 
      }
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
              children: secondArea.School.map(School => ({
                SubClass: School.SchoolName,
                value: School.SchoolID,
                level: 4,
              }))
          }))
        }))
      }
    },
    // 获取资产树
    async GetDeviceStatusSumTree() {
      const res = await connrequest('GetDeviceStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    async changeMailGlobal(row){
      this.logList = {...row}
      this.logDialog = true
    },
    findBaselineLabel(BlID) {
      const baselineItem = this.BaselineResultList.find(item => item.value === BlID);
      return baselineItem ? baselineItem.label : '';
    },
    findBaselineFixScheme(BlID) {
      const baselineItem = this.BaselineResultList.find(item => item.value === BlID);
      return baselineItem ? baselineItem.FixScheme : '';
    },
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按日统计趋势':
          this.GetZeroTrustLogSumGroupByDate()
          break;
        case '按用户统计分析':
          this.GetZeroTrustLogSumGroupByUser()
          break;
        default:
          this.GetKingVirusLogSumGroupByVirusType()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按日统计趋势'){
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog(this.searchobj)
      }else if(title === '按用户统计分析'){
        this.searchobj = { UserId: val }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计趋势':
          this.GetZeroTrustLogSumGroupByDate()
          break;
        case '按用户统计分析':
          this.GetZeroTrustLogSumGroupByUser()
          break;default:
          this.GetKingVirusLogSumGroupByVirusType()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          UserId: this.searchform.UserId,
          ...searchobj
        }
      }
      const res = await connrequest('GetZeroTrustLog', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging?.TotalCount
    },
    // 获取事件日期统计
    async GetZeroTrustLogSumGroupByDate(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          UserId: this.searchform.UserId,
        }
      }
      const res = await connrequest('GetZeroTrustLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.barchartData = {xAxis,series}
    },
    // 按用户统计分析
    async GetZeroTrustLogSumGroupByUser(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          UserId: this.searchform.UserId,
        }
      }
      const res = await connrequest('GetZeroTrustLogSumGroupByUser', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr 
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime() 
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'NeedFix', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
::v-deep .el-descriptions-item__label.is-bordered-label{
  width: 200px;
}
</style>